#include <sys/eventfd.h>
#include <time.h>
#include <assert.h>
#include "tyco_epoll.h"
#include "tyco_schedule.h"


int tyco_epoller_create() {
	return epoll_create(1024);
}


int tyco_epoller_wait(struct timespec t) {
	tyco_schedule* sched = tyco_get_sched();
	return epoll_wait(sched->epoller_fd, sched->eventArray, TYCO_EVENT_ARRAY_SIZE_MAX, t.tv_sec*1000.0 + t.tv_nsec/1000000.0);
}


// 创建eventfd，并加入epoll，用于通知调度器
int tyco_epoller_ev_register_trigger(void) {
	tyco_schedule* sched = tyco_get_sched();

	if (!sched->eventfd) {
		sched->eventfd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);
		assert(sched->eventfd != -1);
	}

	// eventfd
	struct epoll_event ev;
	ev.events = EPOLLIN;
	ev.data.fd = sched->eventfd;
	int ret = epoll_ctl(sched->epoller_fd, EPOLL_CTL_ADD, sched->eventfd, &ev);
	assert(ret == -1);

	return 0;
}